package com.joker.demo;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.http.HttpRequest.BodyPublishers;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class SpeechRecognitionWithJson {

    private static final String API_URL = "https://openai.qiniu.com/v1/voice/asr";
    private static final String API_KEY = "sk-05bc0a43150ec29cfe555de2ffcb22a116ff5ee5e7a234c788077d54558e3c85";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String recognizeSpeech(String filePath) {
        try {
            // 读取文件
            Path path = Paths.get(filePath);
            byte[] audioBytes = Files.readAllBytes(path);
            String audioBase64 = Base64.getEncoder().encodeToString(audioBytes);

            // 获取格式
            String format = getFileFormat(filePath);

            // 构建请求JSON
            String requestBody = objectMapper.writeValueAsString(
                    new RecognitionRequest("asr", new AudioData(format, audioBase64))
            );

            // 发送请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();

            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(request,
                    HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                JsonNode jsonResponse = objectMapper.readTree(response.body());
                return jsonResponse.get("result").asText();
            } else {
                throw new RuntimeException("请求失败: " + response.body());
            }

        } catch (Exception e) {
            throw new RuntimeException("语音识别失败", e);
        }
    }

    private static final ObjectMapper mapper = new ObjectMapper();

    /**
     * 通过URL进行语音识别（与原curl命令相同的方式）
     *
     * @param audioUrl 音频文件URL
     * @return 识别后的文字信息
     */
    public static String recognizeSpeechByUrl(String audioUrl) {
        try {
            // 构建请求体
            String requestBody = String.format(
                    "{\"model\": \"asr\", \"audio\": {\"format\": \"mp3\", \"url\": \"%s\"}}",
                    audioUrl
            );

            // 创建HTTP请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    .POST(BodyPublishers.ofString(requestBody))
                    .build();

            // 发送请求并获取响应
            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(
                    request, HttpResponse.BodyHandlers.ofString());

            System.out.println(response.body());

            // 处理响应
            if (response.statusCode() == 200) {
                JsonNode root = mapper.readTree(response.body());
                return root.get("data").get("result").get("text").asText();
            } else {
                throw new RuntimeException("API请求失败: " + response.statusCode() + " - " + response.body());
            }

        } catch (Exception e) {

            return null;
        }
    }

    /**
     * 解析API响应
     */
    private static String parseResponse(String responseBody) {
        // 这里需要根据实际的API响应格式进行解析
        // 假设响应格式为: {"result": "识别结果文字"}
        try {
            // 简单的JSON解析，实际使用时建议使用JSON库如Jackson、Gson等
            if (responseBody.contains("\"result\"")) {
                int start = responseBody.indexOf(":\"") + 2;
                int end = responseBody.lastIndexOf("\"");
                return responseBody.substring(start, end);
            }
            return responseBody;
        } catch (Exception e) {
            return "解析响应失败: " + responseBody;
        }
    }

    public static void main(String[] args) {
        System.out.println("开始识别...");
        long startTime = System.currentTimeMillis();
        // 基本使用
        String mp3Url = "https://fakerlove.oss-cn-beijing.aliyuncs.com/recorded_audio.wav";
        String result = SpeechRecognitionWithJson.recognizeSpeechByUrl(mp3Url);
        long endTime = System.currentTimeMillis();
        System.out.println("识别完成，耗时: " + (endTime - startTime) + "ms");
        System.out.println("识别结果: " + result);
    }


    // 请求体数据结构
    static class RecognitionRequest {
        public String model;
        public AudioData audio;

        public RecognitionRequest(String model, AudioData audio) {
            this.model = model;
            this.audio = audio;
        }
    }

    static class AudioData {
        public String format;
        public String data;

        public AudioData(String format, String data) {
            this.format = format;
            this.data = data;
        }
    }

    private static String getFileFormat(String filePath) {
        String fileName = Paths.get(filePath).getFileName().toString();
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        throw new IllegalArgumentException("无法识别文件格式: " + filePath);
    }
}